function playSound(url) {
    $('embed').remove();
    $('body').append("<embed src='" + url + "' autostart='true' hidden='true' loop='false'>");
}

function enterPressed() {
    if (window.event && window.event.keyCode == 13) {
        if ($('#typeChat option:selected').text() == 'Ajax chat')
            sendMessAjax();
        else
            sendMessYahoo();
    }
}
function processChat(name) {
    var tab = $('#tabs').tabs();
    var isHave = false;
    $("#tabs a").each(function (i) {
        if (this.text == name) {
            $("#tabs").tabs("option", "selected", i);
            isHave = true;
            return true;
        }
    });

    if (isHave == false)
        addTab(name);
}

function addTab(data) {
    var tab = $('#tabs').tabs();
    var li = "<li><a href=\'#" + data + "\'>" + data + "</a><span  class=\"ui-icon ui-icon-close\"></span></li>";
    tab.find(".ui-tabs-nav").append(li);
    tab.append("<div id='" + data + "'></div>");
    tab.tabs("refresh");
    $("#tabs").tabs("option", "selected", $("#tabs li").length - 1);
}

function sendMessAjax() {
    var mess = $("#messageInput").val();
    $('#messageInput').val('');
    var fromUser = $('#select').text();
    var index = $("#tabs").tabs("option", "selected");
    var toUser = '';
    $("#tabs a").each(function (i) {
        if (i == index) {
            toUser = this.text;
            return true;
        }
    });
    if (toUser != 'Main Chat' && mess != '') {
        var requestURL = 'http://localhost:53220/api/message?fromuser=' + fromUser + "&touser=" + toUser + '&mess=' + mess;
        $.ajax({
            url: requestURL,
            type: 'POST',
            success: function (data) {
                var innerHTML = "<p><strong style='color: yellow;'>" + fromUser + "</strong>: " + data + "</p>";
                $('#' + toUser).append(innerHTML);
            }
        });
    }
    else
        alert('Message is null or no friend been selected!');
}

function sendMessYahoo() {
    var mess = $("#messageInput").val();
    $('#messageInput').val('');
    var index = $("#tabs").tabs("option", "selected");
    var toUser = '';
    $("#tabs a").each(function (i) {
        if (i == index) {
            toUser = this.text;
            return true;
        }
    });
    if (toUser != 'Main Chat' && mess != '') {
        var requestURL = 'http://localhost:53220/api/yahoomessage?user=' + toUser + '&mess=' + mess + "&oauth_token=" + $('#oauth_token').text() + "&oauth_token_secret=" + $('#oauth_token_secret').text() + "&sessionID=" + $('#sessionID').text(); ;
        $.ajax({
            url: requestURL,
            type: 'POST',
            success: function (data) {
                var innerHTML = "<p><strong style='color: yellow;'>" + $('#select').text() + "</strong>: " + data + "</p>";
                $('#' + toUser).append(innerHTML);
            }
        });
    }
    else
        alert('Message is null or no friend been selected!');
}
$(document).ready(function () {
    document.onkeypress = enterPressed;

    var tab = $('#tabs').tabs();
    $("#tabs span.ui-icon-close").live("click", function () {
        var panelId = $(this).closest("li").remove().attr("aria-controls");
        var text = $(this).closest("li").text();
        $("#" + text).remove();
        $('#list li ul li').removeClass(text);
        tab.tabs("refresh");
    });

    $(document).on("click", "#list li ul li", function () {
        var temp = $(this).parent().parent().text();
        var name = temp.substring(0, temp.indexOf("\n")) || temp.substring(0, temp.indexOf(" "));
        if ($(this).text().trim() == 'Chat') {

            if (!$(this).hasClass(name)) {
                addTab(name);
                $(this).addClass(name);
            }
            else {
                $("#tabs a").each(function (i) {
                    if (this.text == name) {
                        $("#tabs").tabs("option", "selected", i);
                        return true;
                    }
                });
            }
        }
        else {
            deleteFriend(name);
        }
    });

    $("#sendButton").click(function () {
        if ($('#typeChat option:selected').text() == 'Ajax chat')
            sendMessAjax();
        else
            sendMessYahoo();
        //recvMessYahoo();
    });


});

function recvMessAjax() {
    var username = $('#select').text();
    var requestURL = 'http://localhost:53220/api/message?user=' + username;
    $.ajax({
        url: requestURL,
        type: 'GET',
        complete: recvMessAjax,
        timeout: 30000,
        success: function (data) {
            if (data != null) {
                data.forEach(function (ms) {
                    var n = ms.indexOf('@', 0);
                    var user = ms.substring(0, n);
                    var mess = ms.substring(n + 1, ms.length);
                    if ($('#' + user).length) {
                        var innerHTML = "<p><strong style='color: blue;'>" + user + "</strong>: " + mess + "</p>";
                        $('#' + user).append(innerHTML);
                    }
                    else
                        CreateTab(user, mess);
                });
            }
        }
    });
}

function recvMessYahoo() {
    var requestURL = "http://localhost:53220/api/yahoomessage?oauth_token=" + $('#oauth_token').text() + "&oauth_token_secret=" + $('#oauth_token_secret').text() + "&sessionID=" + $('#sessionID').text() + "&seq=" + $('#seq').text();
    $.ajax({
        url: requestURL,
        type: 'GET',
        complete: recvMessYahoo,
        timeout: 30000,
        success: function (data) {
            if (data != null) {
                data.forEach(function (ms) {
                    var n = ms.indexOf('@', 0);
                    if (n >= 0) {
                        var user = ms.substring(0, n);
                        var mess = ms.substring(n + 1, ms.length);
                        if ($('#' + user).length) {
                            var innerHTML = "<p><strong style='color: blue;'>" + user + "</strong>: " + mess + "</p>";
                            $('#' + user).append(innerHTML);
                        }
                        else
                            CreateTab(user, mess);
                        playSound('sound/message.wav');
                    }
                    else
                        $('#seq').text(ms);
                });

            }
        }
    });
}

function CreateTab(data, mess) {
    li = "<li><a href=\'#" + data + "\'>" + data + "</a><span  class=\"ui-icon ui-icon-close\"></span></li>";
    var tab = $('#tabs').tabs();
    tab.find(".ui-tabs-nav").append(li);
    tab.append("<div id='" + data + "'></div>");
    tab.tabs("refresh");
    var innerHTML = "<p><strong style='color: blue;'>" + data + "</strong>: " + mess + "</p>";
    $('#' + data).append(innerHTML);
}
				
	